#include<iostream>
using namespace std;

void NewspaperSegmentation::computeStep3Image(){
	if( image_step[2] == 0 )
		computeStep2Image();
	if( image_step[3] ){
		setCurrentImage( 3 );
		//QMessageBox::about ( this, QString("Otsu"), QString("Binarizacao em k* = %1 e eta* = %2").arg(k_max).arg(eta) );
		return;
	}
	//implementar limiarização de otsu aqui
	
	if( histogram[2] == 0 ){
		histogram[2] = new vector<float>(256,0);
	
		for( int y = 0; y < image_step[2]->height(); ++y ){
			for( int x = 0; x < image_step[2]->width(); ++x ){
				int k = qRed(image_step[2]->pixel( x, y ));
				(*histogram[2])[k] += 1;
			}
		}
	}
	
	int MN = image_step[2]->width()*image_step[2]->height();
	
	//otsu passo 1
	vector<float> p( 256 );
	for( int i = 0; i < 256; ++i )
		p[i] = (*histogram[2])[i] / MN;
	
	//otsu passo 2
	vector<float> P(256,0);
	P[0] = p[0];
	for( int i = 1; i < 256; ++i )
		P[i] = P[i-1] + p[i];
	
	//otsu passo 3
	vector<float> m(256,0);
	m[0] = 0;
	for( int i = 0; i < 256; ++i )
		m[i] = m[i-1] + i*p[i];
	
	//otsu passo 4
	float mg = m[255];
	
	//otsu passo 5
	vector<float> sigmab2(256,0);
	int k_sigma_max = 0;
	for( int k = 0; k < 256; ++k ){
		if( P[k] > 0 && P[k] < 1 )
			sigmab2[k] = ((mg*P[k]-m[k])*(mg*P[k]-m[k])) / (P[k]*(1-P[k]));

		if( sigmab2[k] > sigmab2[k_sigma_max] )
			k_sigma_max = k;
	}
	
	//for( int k = 0; k < 256; k++ )
	//	cout << P[255] << " ";
	
	//otsu passo 6
	int count_qtd_k_sigma_max = 0;
	k_max = 0;
	for( int k = 0; k < 256; ++k ){
		if( sigmab2[k] == sigmab2[k_sigma_max] ){
			k_max = k_max + k;
			count_qtd_k_sigma_max++;
		}
	}
	k_max = k_max/count_qtd_k_sigma_max;
	
	//ostu passo 7
	float sigmag2 = 0;
	for( int i = 0; i < 256; ++i )
		sigmag2 = sigmag2 + ( i - mg )*( i - mg )*p[i];
	
	
	eta = sigmab2[k_max]/sigmag2;

	//limiarição
	image_step[3] = new QImage( image_step[2]->width(), image_step[2]->height(), QImage::Format_RGB32 );
	
	for( int y = 0; y < image_step[3]->height(); ++y ){
		for( int x = 0; x < image_step[3]->width(); ++x ){
			if( qRed(image_step[2]->pixel( x, y ) ) > k_max )
				image_step[3]->setPixel( x, y, QColor( 255, 255, 255 ).rgb() );
			else
				image_step[3]->setPixel( x, y, QColor( 0, 0, 0 ).rgb() );
		}
	}
	
	//término da implementação
	setCurrentImage( 3 );
	//QMessageBox::about ( this, QString("Otsu"), QString("Binarizacao em k* = %1 e eta* = %2").arg(k_max).arg(eta) );
}

